import { EventNames, emitter } from "@renderer/services/event-service";
import type { RefObject } from "react";
import { useEffect, useRef } from "react";

interface UseSettingsFocusOptions {
  enabled?: boolean;
  delay?: number;
  focusOnMount?: boolean;
}

export function useSettingsFocus(
  tabsRef: RefObject<HTMLDivElement | null>,
  options: UseSettingsFocusOptions = {},
) {
  const { enabled = true, delay = 100, focusOnMount = true } = options;
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const focusSettings = useRef(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      if (tabsRef.current) {
        // Focus on the tabs container or the first focusable element within it
        const firstTab = tabsRef.current.querySelector(
          '[role="tab"]',
        ) as HTMLElement;
        if (firstTab) {
          firstTab.focus();
        } else {
          tabsRef.current.focus();
        }
      }
    }, delay);
  });

  // Update the focus function when delay changes
  useEffect(() => {
    focusSettings.current = () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }

      timeoutRef.current = setTimeout(() => {
        if (tabsRef.current) {
          const firstTab = tabsRef.current.querySelector(
            '[role="tab"]',
          ) as HTMLElement;
          if (firstTab) {
            firstTab.focus();
          } else {
            tabsRef.current.focus();
          }
        }
      }, delay);
    };
  }, [delay, tabsRef]);

  // Focus on mount (initial load or when navigating to settings)
  useEffect(() => {
    if (enabled && focusOnMount) {
      focusSettings.current();
    }
  }, [enabled, focusOnMount]);

  useEffect(() => {
    if (!enabled) return;

    const handleTabSelect = () => {
      focusSettings.current();
    };

    const unsub = emitter.on(EventNames.TAB_SELECT, handleTabSelect);

    return () => {
      unsub();
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [enabled]);

  return {
    focusSettings: () => focusSettings.current(),
  };
}
